package com.booza.dao;

import java.util.Date;
import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import com.booza.exceptions.WireCardException;
import com.booza.model.WireCardPayin;

public class WirecardPayinDAOImpl implements WirecardPayinDAO
{
	@Autowired
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory()
	{
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory)
	{
		this.sessionFactory = sessionFactory;
	}

	@Override
	public WireCardPayin findWireCardPayin(Integer id)
	{
		return (WireCardPayin) sessionFactory.getCurrentSession().get(WireCardPayin.class, id);
	}

	@Override
	public void insertWireCardPayin(WireCardPayin wp)
	{
		if (wp.getTransactionDate() == null) {
			wp.setTransactionDate(new Date());
		}
		sessionFactory.getCurrentSession().save(wp);
	}

	@Override
	public void updateWireCardPayin(WireCardPayin wp)
	{
		sessionFactory.getCurrentSession().saveOrUpdate(wp);
	}

	@Override
	public WireCardPayin findWireCardPayinByGuWid(String guWid) throws WireCardException
	{
		Session session = sessionFactory.getCurrentSession();
		List payins = session.createCriteria(WireCardPayin.class).add(Restrictions.eq("guWid", guWid)).list();
		WireCardPayin payin = null;
		if (payins == null || payins.size() != 1) {
			throw new WireCardException("Wirecard payin details not found in db" + guWid);
		}
		return (WireCardPayin) payins.get(0);
	}
}
